<template>
  <div class="base-info-lay">
    <el-form :model="data" :rules="rules" ref="myForm">
      <template v-for="(item) in columns" :key="item.id">
        <el-form-item v-if="item.canEdit !== false" :prop="item.id" :label="item.name"
                      v-model="data[item.id]" :label-width="formLabelWidth">
          <el-select v-if="item.type === 'select'" v-model="data[item.id]" style="width: 100%"
                     :disabled="item.readOnly" @change="selectChange(item, data[item.id])">
            <el-option
                v-for="option in item.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
          <el-tree-select
              v-else-if="item.type === 'tree'"
              v-model="data['parentId']"
              :disabled="data['disabled']"
              clearable
              :data="data['treeData']"
              check-strictly
              highlight-current
              :title="123"
              :render-after-expand="false"
              :default-expand-all="true"
              @change="selectTreeChange(item)"
              style="width: 100%"
          />
          <el-input :readonly="!!item.readOnly" v-else :key="item.id" v-model="data[item.id]"/>
        </el-form-item>
      </template>
    </el-form>
    <div>
      <el-form-item style="display: flex;flex-direction: row;">
        <div style="flex: 1"/>
        <el-button @click="() => { isShow = false; }" style="padding: 0 24px 0;">取消</el-button>
        <el-button type="primary" @click="onSummit" style="padding: 0 24px 0;">
          确定
        </el-button>
      </span>
      </el-form-item>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref} from "vue";

const title = ref('');

interface BaseInfoConfig {
  submit: any;
  columns: any;
  rules: any;
  formLabelWidth: number;
}

const props = defineProps<BaseInfoConfig>();
const data = ref<Record<string, any>>({});
const editType = ref('add');
const isShow = ref(false);
const myForm = ref(null);

const selectChange = (item: any, val: any) => {
  if (item.selectChanged) {
    item.selectChanged(props.columns, val);
  }
}

const selectTreeChange = (item: any) => {

}

const onSummit = async () => {
  const valid = await myForm.value?.validate();
  if (valid) {
    isShow.value = false;
    if (props.submit) {
      await props.submit(data.value, editType.value);
    }
  }
}

const edit = (t: string, item: Record<string, any>, type: string) => {
  title.value = t;
  data.value = {...item};
  editType.value = type;
  isShow.value = true;
}

const editAdd = (t: string, item: Record<string, any>) => {
  edit(t, item, 'add');
}

const editUpdate = (t: string, item: Record<string, any>) => {
  edit(t, item, 'update');
}

defineExpose({
  editAdd,
  editUpdate
})

</script>

<style scoped>
.base {
  margin: 16px;
  display: flex;
  flex-direction: column;
}

</style>
